import os
import pandas as pd
import pickle
import re
import time
import datetime
import warnings
warnings.filterwarnings('ignore')
from get_data.tusharecopy.stock import wencaicopy
from stock import chajian
import functools
import other
from get_data import Altas_db
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

_1_, time_, _2_ = other.time_start()
#____________________________
def dxw_gegutosave(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        t1 = time.time()
        res = func(*args, **kwargs)
        if kwargs["time_"]==None:
            time_ = other.time_saveandget()
        if kwargs["time_"]=="":
            time_ = other.time_saveandget()
        else:
            time_=kwargs["time_"]

        if func.__name__=="ths_vol":
            Altas_db._save_mongo_db(res,"ths_vol","{}_zvol".format(time_))
        if func.__name__=="ths_price":
            Altas_db._save_mongo_db(res, "ths_vol", "{}_zpri".format(time_))
        # res.to_csv(path["vol_"].format(time_), encoding="utf-8")
        #print("运行时间{}s".format(time.time()-t1),"开始保存到tushare_his/other/{}_vol.json中".format(time_))
    return wrapper
@dxw_gegutosave
def ths_vol(num=2,time_=""):
    name = "{}成交量，5日成交量，30日成交量，120日成交量".format(time_)
    df = wencaicopy.searchMain(name, num)

    df=chajian.ths_vol_df(df)
    #print(df)
    return df

def today_vol_read(day=time_):
    if day == "":
        global time_
        day = time_
        print(day)
    #print(day)
    #获取文件夹中最大的名字
    #os_json_name=max(os.listdir(path["other"]))#20211024_vol.json
    list_i= Altas_db.client["ths_vol"].collection_names()
    df = pd.DataFrame(list_i)
    df = df[df[0].str.contains('zvol')]
    list_i = df[0].tolist()
    os_json_name = max(list_i)
    #os_json_name=max(Altas_db.client["ths_vol"].collection_names())
    os_json_name_str=os_json_name[:4]+"-"+os_json_name[4:6]+"-"+os_json_name[6:8]
    day_name_str=day[:4]+"-"+day[4:6]+"-"+day[6:8]
    date1 = datetime.datetime.strptime(os_json_name_str, "%Y-%m-%d")
    date2 = datetime.datetime.strptime(day_name_str, "%Y-%m-%d")
    print("{}_zvol".format(day) ==os_json_name)
    if "{}_zvol".format(day) ==os_json_name:
        # 7天以内，不用更新
        #df = pd.read_csv(path["vol_"].format(day), encoding="utf-8", index_col=0)
        df=Altas_db._readdf("ths_vol","{}_zvol".format(day))
        print("当日读取完成",os_json_name)
        return df
    if abs(date1 - date2).days<7:
        # 7天以内，不用更新
        # if "zt"in os_json_name:
        #     os_json_name=os.listdir(path["other"])[-2]
        #df = pd.read_csv(path["vol_"].format(os_json_name[:8]), encoding="utf-8", index_col=0)
        #print("7天以内读取完成",path["vol_"].format(os_json_name[:8]))
        df=Altas_db._readdf("ths_vol","{}_zvol".format(os_json_name[:8]))
        print("7天以内读取完成",os_json_name)
        return df
    else:
        print("没有数据","1.获取数据，2.然后重新运行，走ifos.path.exists")
        ths_vol(num=2, time_=day)
        df=today_vol_read(day=day)
        return df
# ____________________________
@dxw_gegutosave
def ths_price(num=2,time_=""):
    name = "{}，5日均线20日均线50日均线250均线".format(time_)
    df = wencaicopy.searchMain(name, num)
    df=chajian.ths_price_df(df)
    return df
# @other.time_
def today_volAndpri_read(day=time_,dtype="vol",page_num=200):
    """
    作为today_vol_read升级产品，兼容ths_price/ths_vol
    :param day:
    :param dtype:vol
                 pri
    :return:
    """
    if day == "":
        global time_
        day = time_
    #print(day)
    #获取文件夹中最大的名字
    #os_json_name=max(os.listdir(path["other"]))#20211024_vol.json
    os_json_name =Altas_db._read_ths_volMax(dtype=dtype,model="returnMaxName")

    #os_json_name=max(Altas_db.client["ths_vol"].collection_names())
    os_json_name_str=os_json_name[:4]+"-"+os_json_name[4:6]+"-"+os_json_name[6:8]
    day_name_str=day[:4]+"-"+day[4:6]+"-"+day[6:8]
    date1 = datetime.datetime.strptime(os_json_name_str, "%Y-%m-%d")
    date2 = datetime.datetime.strptime(day_name_str, "%Y-%m-%d")

    if "{}_z{}.json".format(day,dtype) ==os_json_name:
        # 7天以内，不用更新
        #df = pd.read_csv(path["vol_"].format(day), encoding="utf-8", index_col=0)
        df=Altas_db._readdf("ths_vol","{}_z{}".format(day,dtype))
        print("当日读取完成",os_json_name)
        return df
    if abs(date1 - date2).days<7:
        # 7天以内，不用更新
        # if "zt"in os_json_name:
        #     os_json_name=os.listdir(path["other"])[-2]
        #df = pd.read_csv(path["vol_"].format(os_json_name[:8]), encoding="utf-8", index_col=0)
        #print("7天以内读取完成",path["vol_"].format(os_json_name[:8]))
        df=Altas_db._readdf("ths_vol","{}_z{}".format(os_json_name[:8],dtype))
        print("7天以内读取完成",os_json_name)
        return df
    else:
        print("没有数据","1.获取数据，2.然后重新运行，走ifos.path.exists")
        if dtype=="vol":
            print("运行vol，请耐心等待")
            ths_vol(num=page_num, time_=day)
            df = today_volAndpri_read(day=day, dtype="vol")
        if dtype == "pri":
            print("运行pri，请耐心等待")
            ths_price(num=page_num, time_=day)
            df = today_volAndpri_read(day=day, dtype="pri")
        return df

# ____________________________

def zt(time_=time_):
    name="{}涨停和涨停原因及资金".format(time_)#20211021涨停和涨停原因及资金
    df = wencaicopy.searchMain(name, 10)
    print(df)
    df=chajian.zt_df(df)
    Altas_db._save_mongo_db(df,"iwencai\zt","{}".format(time_))
    # time_=re.findall("\d+",name)[0]
    #df.to_csv(path["zt"], encoding="utf-8")
    return df
def zt_(name,num=10):

    df = wencaicopy.searchMain(name, num)
    print(df)
    # df=chajian.zt_df(df)
    # Altas_db._save_mongo_db(df,"iwencai\zt","{}".format(time_))
    return df
if __name__ == '__main__':
    # 1.当日涨停
    zt()
    # 2."成交量，5日成交量，30日成交量，120日成交量"
    #ths_vol(num=2,time_="20210109")
    #>>>today_vol_read()
    #ths_price(num=2, time_="20210109")

    today_volAndpri_read(dtype="pri")
    # 可用代替MA120
    # 3.人气排名
    # name="20210909人气概念板块排名"
    #name = "20211119人气及行业板块"
    # print(wencaicopy.searchMain(name, 10))
